package com.drinks.yiniang.ui.widget.dialog;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.widget.ContentLoadingProgressBar;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;

import com.drinks.yiniang.R;
import com.drinks.yiniang.adapter.listview.CouponSelectorAdapter;
import com.drinks.yiniang.entity.user.order.OrderConfirmJson;
import com.drinks.yiniang.entity.user.order.OrderCouponJson;
import com.drinks.yiniang.io.api.OrderApiIO;
import com.drinks.yiniang.utils.ToastUtils;
import com.hansen.library.Constants;
import com.hansen.library.io.tuple.Tuple2;
import com.hansen.library.listener.APIRequestCallback;
import com.hansen.library.listener.CheckDoubleClickListener;
import com.hansen.library.ui.widget.dialog.BaseDialogFragment;
import com.hansen.library.utils.CommonUtils;
import com.hansen.library.utils.LogUtils;
import com.hansen.library.utils.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 退款原因dialog
 *
 * @author han
 * @date 2019/11/12
 */
public class CouponSelectorDialog extends BaseDialogFragment implements AdapterView.OnItemClickListener {

    //退款原因列表
    private ListView lv_coupon_select_dialog;
    private ContentLoadingProgressBar progress_order_coupon_dialog;
    //关闭
    private Button btn_coupon_select_close;

    private CouponSelectorAdapter mCouponSelectorAdapter;

    private OnCouponChooseListener onCouponChooseListener;

    private List<OrderCouponJson.OrderCouponData> mList;

    private String mShopId;
    private String mOrderPrice;

    private int mCurrentChoosePostion = -1;

    public static CouponSelectorDialog newInstance(String shopId, String orderPrice) {

        Bundle bundle = new Bundle();
        bundle.putString(Constants.KeyId, shopId);
        bundle.putString(Constants.KeyMoney, orderPrice);

        CouponSelectorDialog dialog = new CouponSelectorDialog();
        dialog.setArguments(bundle);

        return dialog;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            onCouponChooseListener = (OnCouponChooseListener) context;
        } catch (ClassCastException e) {
            LogUtils.e(context.toString() + "must implement OnCouponChooseListener");
        }
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // 定义Dialog布局和参数
        mDialog = new Dialog(getActivity(), R.style.ActionSheetDialogStyle);

        // 获取Dialog布局
        View mView = LayoutInflater.from(getActivity()).inflate(
                R.layout.dialog_coupon_selector, null);

        mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // 设置Content前设定
        mDialog.setContentView(mView);
        mDialog.setCanceledOnTouchOutside(true);
        mDialog.setCancelable(true);

        Window dialogWindow = mDialog.getWindow();
        dialogWindow.setGravity(Gravity.LEFT | Gravity.BOTTOM);
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();

        lp.gravity = Gravity.BOTTOM; // 紧贴底部
        lp.dimAmount = 0.5f;
        lp.width = WindowManager.LayoutParams.MATCH_PARENT; // 宽度持平

        dialogWindow.setAttributes(lp);
        dialogWindow.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);

        lv_coupon_select_dialog = mView.findViewById(R.id.lv_coupon_select_dialog);

        progress_order_coupon_dialog = mView.findViewById(R.id.progress_order_coupon_dialog);

        btn_coupon_select_close = mView.findViewById(R.id.btn_coupon_select_close);

        lv_coupon_select_dialog.setOnItemClickListener(this);

        btn_coupon_select_close.setOnClickListener(new CheckDoubleClickListener() {
            @Override
            public void onCheckDoubleClick(View v) {
                dismiss();
            }
        });

        initData();

        return mDialog;
    }

    private void initData() {
        mContext = getActivity();

        mList = new ArrayList<>();

        mCouponSelectorAdapter = new CouponSelectorAdapter(mContext, mList);

        lv_coupon_select_dialog.setAdapter(mCouponSelectorAdapter);

        mShopId = getArguments() != null ? getArguments().getString(Constants.KeyId) : null;
        mOrderPrice = getArguments() != null ? getArguments().getString(Constants.KeyMoney) : null;

        getCoupon();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (CommonUtils.isArrayIndexOutOfBounds(mList, position)) {
            return;
        }

        if (!CommonUtils.isArrayIndexOutOfBounds(mList, mCurrentChoosePostion)) {
            mList.get(mCurrentChoosePostion).setChecked(false);
        }

        OrderCouponJson.OrderCouponData data = mList.get(position);
        data.setChecked(true);
        mList.set(position, data);

        mCurrentChoosePostion = position;

        mCouponSelectorAdapter.notifyDataSetChanged();

        if (onCouponChooseListener != null) {
            onCouponChooseListener.onCouponChooseClick(data.getId(), data.getAmount());
        }

        dismiss();
    }

    //获取优惠券
    private void getCoupon() {
        if (StringUtils.isEmpty(mOrderPrice)) {
            return;
        }

        progress_order_coupon_dialog.show();

        OrderApiIO.getInstance().getOrderCoupon(mShopId, mOrderPrice, new APIRequestCallback<OrderCouponJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(OrderCouponJson res) {
                if(mList == null) {
                    return;
                }

                mList.clear();
                mList.addAll(res.getData());
                mCouponSelectorAdapter.notifyDataSetChanged();
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                if(progress_order_coupon_dialog != null) progress_order_coupon_dialog.hide();
            }
        });
    }

    @Override
    public void onDestroy() {
        mDialog = null;
        super.onDestroy();
    }

    public interface OnCouponChooseListener {
        void onCouponChooseClick(String code, String value);
    }
}
